<?php
 
$guid = $vars["entity"]->guid;
$userLogged = elgg_get_logged_in_user_entity();


// Task: get skill and UserSkill object
$lstSkillGloble = elgg_get_entities(array(
		'type' => 'object',
		'subtype' => 'skill',
));
$lstUserSkills = elgg_get_entities(array(
		'type'=>'object',
		'subtype'=>'UserSkill',
		'owner_guid'=>$userLogged->guid,
));

// Task: get guid input
$guidSkills_Input = get_input('skill_guids');
$skil_Guids_Array = explode(" ", $guidSkills_Input);

// Task: Delete skill
deleteSkill($skil_Guids_Array, $lstUserSkills);

if($guidSkills_Input != ""){	
	// Task: save user skill
		// If the input guid has not existed in user skill -> create a userskill
	foreach ($skil_Guids_Array as $inputGuidValue){
		$skillItem = get_entity($inputGuidValue);
		if(isset($skillItem) && !isExited($skillItem, $lstUserSkills)){
			$userSkill_Obj = new ElggObject();
			$userSkill_Obj->type = "object";
			$userSkill_Obj->subtype = "UserSkill";
			$userSkill_Obj->owner_guid = $userLogged->guid;
			$userSkill_Obj->title = $skillItem->title;
			$userSkill_Obj->description = $skillItem->description;
			$userSkill_Obj->access_id = 1;
			$userSkill_Obj->save();
		}
	}
	
}

$username = $userLogged->username;
// Task: forward to profile page
if($username){
	forward('profile/' . $username);
} else {
	forward('');
}

/**
 * get all skill object have the same 
 * @param unknown $arrayGuidInput
 * @return multitype:
 */
function getListSkillObjInput($arrayGuidInput){
	$listSkillObj = array();
	foreach($arrayGuidInput as $guidValue){
		$skill = get_entity($guidValue);
		if(isset($skill)){
			array_push($listSkillObj, $skill);
		}
	}
	return $listSkillObj;
}

/**
 * Delete skills which is not existed in UserSkills
 * @param array<String> $arrayGuid
 * @param Array<UserSkill> $listUserSkills
 */
function deleteSkill($arrayGuid, $listUserSkills){
	// Task: Get input skill list
	$lstInputSkill = getListSkillObjInput($arrayGuid);
	// Task: Delete skill 
	if(isset($lstInputSkill)){
		foreach ($listUserSkills as $userSkillValue){
			if(!isExited($userSkillValue, $lstInputSkill))
			{
				delete_entity($userSkillValue->guid);
			}
		}
	}

}


/**
 * Check if a skill(SkillName) is existed in userskills or not.
 * @param String $skillName
 * @param array $listSkills
 * @return boolean
 */
function isExited($skill, $listSkill){

	foreach ($listSkill as $value){
		if($value->title == $skill->title){
			return true;
		}
	}
	return false;
}
?>